package org.example.websocket;

import cn.hutool.core.lang.Console;
import org.example.domain.CountSingleton;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {

    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());
    private Session session;

    // 广播全部，包括自己
    public static void broadcast(String message) throws IOException {
        for (Session session : sessions) {
            session.getBasicRemote().sendText(message);
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        sessions.add(session);
        this.sendMessage(String.valueOf(CountSingleton.getCount()));

        // hutool工具里的Console.log方法，优雅拼接参数，基于System.out封装。
        Console.log("新建连接：{}", session.getId());
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        Console.log("连接关闭：{}", session.getId());
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
